package com.example.demo.controller;

import com.example.demo.utils.AjaxResult;
import com.google.code.kaptcha.Producer;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.example.demo.config.SelfFinalProperty.VC_PREFIX;
import static com.example.demo.config.SelfFinalProperty.VC_TIME;

@RestController
public class CaptchaController {
    @Resource
    private Producer captchaProducer;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/vc.img")
    public AjaxResult getCode() throws IOException {
        //生成验证码
        String uuid = UUID.randomUUID().toString();
        String captcha = captchaProducer.createText();

        BufferedImage image = captchaProducer.createImage(captcha);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);
        HashMap<String, String> data = new HashMap<>();
        data.put("uuid", uuid);
        data.put("img", Base64.encode(os.toByteArray()));

        //将uuid和captcha放入redis,有效时间10分钟
        redisTemplate.opsForValue().set(VC_PREFIX+uuid,captcha, VC_TIME, TimeUnit.MINUTES);
        return AjaxResult.success(data);
    }
}

